/*******************************************
Module: zt_thread.c
E-Mail: 24zhutian@gmail.com
Notices: Copyright (c) 2007-2011 ls
*******************************************/
#include "zt_config.h"
#include "zt_thread.h"

ZT_API int zt_thread_init(zt_thread_t *pt)
{
	pt->lpfn=NULL;
	pt->args=NULL;
	
	pt->id=0;	
	pt->object=NULL;

	pt->priority=THREAD_PRIORITY_NORMAL;

	pt->initflag=0;
	pt->security=NULL;
	pt->stack_size=0;
	pt->timeout=INFINITE;

	pt->status=ZT_THREAD_RUN;

	pt->abort=0;

	return(ZT_OK);
}

ZT_API u_long zt_thread_start(zt_thread_t *pt,ZT_PTHREAD_START lpfn,void *args)
{
	pt->lpfn=lpfn;
	pt->args=args;

	pt->object=(void *)_beginthreadex(pt->security,pt->stack_size,pt->lpfn,pt->args,pt->initflag,&pt->id);

	return((u_long)pt->object);
}

ZT_API u_long zt_thread_suspend(zt_thread_t *pt)
{
	pt->status=ZT_THREAD_PAUSE;

	return(SuspendThread(pt->object));
}

ZT_API u_long zt_thread_resume(zt_thread_t *pt)
{
	pt->status=ZT_THREAD_RUN;
	return(ResumeThread(pt->object));
}

ZT_API int zt_thread_set_priority(zt_thread_t *pt)
{
	return(SetThreadPriority(pt->object,pt->priority));
}

ZT_API int zt_thread_post_message(zt_thread_t *pt,UINT msg,WPARAM wParam,LPARAM lParam)
{
	return(PostThreadMessage(pt->id,msg,wParam,lParam));
}

ZT_API u_long zt_thread_waitpid(zt_thread_t *pt)
{
	DWORD dw=0;
	dw=WaitForSingleObject(pt->object,pt->timeout);
	if(dw==WAIT_OBJECT_0){
		pt->status=ZT_THREAD_STOP;
	}
	CloseHandle(pt->object);

	return(dw);
}

ZT_API int zt_thread_close(zt_thread_t *pt)
{
	return(CloseHandle(pt->object));
}

ZT_API int zt_thread_exit(zt_thread_t *pt)
{
	DWORD dw=0;
	GetExitCodeThread(pt->object,&dw);
	TerminateThread(pt->object,dw);
	pt->status=ZT_THREAD_STOP;
	return(CloseHandle(pt->object));
}